﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KOPLibrary.DataManagement;
using Microsoft.Office.Interop.Word;

namespace KOPLibrary.Forms
{
    public partial class LabelForm : Form
    {
        public LabelForm()
        {
            InitializeComponent();
        }

        private void LabelForm_Load(object sender, EventArgs e)
        {

        }

        public void Execute(AbstractData data)
        {
            this.data = data;
            ctlDataBindControl.DataSource = data;

            ShowDialog();
        } private AbstractData data;



        private void InsertWithBarcodeField(Microsoft.Office.Interop.Word.Document doc, string text, string barcodeField, int current)
        {
            string barcodeText = data.Eval(current, barcodeField);
            BarcodeLib.Barcode barcode = new BarcodeLib.Barcode();
            barcode.IncludeLabel = ctlDataBindControl.UsedBarcodeSettings.IncludeText;

            string[] parts = text.Split(new string[] { AbstractData.Qualify(barcodeField) }, StringSplitOptions.None);

            try
            {
                for (int i = 0; i < parts.Length; i++)
                {
                    doc.Application.Selection.TypeText(parts[i]);
                    if (i != parts.Length - 1)
                    {
                        Image barcodeImage = barcode.Encode(ctlDataBindControl.UsedBarcodeSettings.BarcodeType, barcodeText, Color.Black, Color.White, ctlDataBindControl.UsedBarcodeSettings.Width, ctlDataBindControl.UsedBarcodeSettings.Height);
                        System.Windows.Forms.Clipboard.SetDataObject(barcodeImage, true);
                        doc.Application.Selection.Paste();
                    }

                }
            }
            catch (Exception exc)
            {
                doc.Application.Selection.TypeText(exc.Message);
            }
        }

        private void ctlGo_Click_1(object sender, EventArgs e)
        {
            bool skipY = false, skipX = false;
            ProgressForm progres = new ProgressForm();
            progres.Initialize(1, data.Count, "Word ile iletişime geçiliyor ...", true, this);
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            WordManager manager = new WordManager(app);

            Microsoft.Office.Interop.Word.Document doc = manager.CreateMailingDocument(true);            
            if (app.ActiveDocument.Tables.Count == 0)
            {
                progres.Done();
                app.Quit();
                return;
            }
            Microsoft.Office.Interop.Word.Table table = app.ActiveDocument.Tables[1];
            if (table.Rows.Count > 1 && table.Rows[1].Height != table.Rows[2].Height)
                skipY = true;
            if (table.Columns.Count > 1 && table.Columns[1].Width != table.Columns[2].Width)
                skipX = true;
            int currentX = 0, currentY = 0;
            string boundText = ctlDataBindControl.BoundText;
            List<string> textBindableFields = data.BindableFields(boundText);
            string barcodeField = string.Empty;

            if (ctlDataBindControl.UsedBarcodeSettings != null)
            {
                barcodeField = ctlDataBindControl.BarcodeField;
                textBindableFields.RemoveAll(p => p.ToString() == barcodeField);
            }            
            for (int i = 0; i < data.Count; i++)
            {
                progres.Update(string.Format("{0} / {1}", i + 1, data.Count));
                try
                {
                    string text = data.Bind(i, boundText, textBindableFields);
                    if (string.IsNullOrEmpty(barcodeField))
                        app.Selection.TypeText(text);
                    else InsertWithBarcodeField(doc, text, barcodeField, i);
                    app.Selection.MoveRight(Unit: WdUnits.wdCell);
                    currentX++;
                    if (currentX == table.Columns.Count)
                    {
                        currentY++;
                        if (skipY && currentY % 2 != 0)
                        {
                            app.Selection.MoveRight(Unit: WdUnits.wdCell, Count: table.Columns.Count);
                            currentY++;
                        }
                        currentX = 0;
                    }
                    else
                    {
                        if (skipX && currentX % 2 != 0)
                        {
                            app.Selection.MoveRight(Unit: WdUnits.wdCell);
                            currentX++;
                        }
                    }                    
                }
                catch (Exception exc)
                {
                    Util.ShowException(exc);
                    if (!Util.Confirm("Etiket işlemine kaldığı yerden devam edilsin mi ?"))
                        break;
                }
            }
            progres.Done();
        }
    }
}
